import { generateJSONName } from '../uuid'
import * as fs from 'fs'
import * as path from 'path'

interface IFileInfo {
  path: string
  filename: string
}

const staticPath = '../../views/public/json/'
function getJSONPath(): IFileInfo {
  const jsonFilename = generateJSONName() + '.json'
  return {
    path: path.join(__dirname, staticPath) + jsonFilename,
    filename: jsonFilename,
  }
}

export async function saveJSON(jsonString: string) {
  if (!jsonString) throw new Error('json字段不能为空')
  const jsonFileName = getJSONPath()
  await fs.writeFileSync(
    jsonFileName.path,
    jsonString,
    {
      encoding: 'utf8',
    }
  )

  return jsonFileName.filename
}
